<?php

namespace App\Repositories\Acl;

use Prettus\Repository\Eloquent\BaseRepository as Repository;
use App\Events\UpdateStaffRoleEvent;

class RoleRepository extends Repository
{

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Acl\Role';
    }

    /**
     * role列表
     *
     * @param string $query
     * @return mixed
     */
    public function index()
    {
        $rows = $this->model->with('permissions')->get();

        foreach($rows as $row)
        {
            //拥有的权限所属父级菜单ID
            $pluck = $row->permissions->pluck('parent')->unique()->values()->all();
            //父级菜单集合
            $parent = \App\Models\Acl\Permission::whereIn('id', $pluck)->get();

            $permissions = $row->permissions->merge($parent)->sortBy('order');
            
            $row->permissions = trees($permissions);
        }
        
        return $rows;
    }

    /**
     * 查找指定role
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function show($id)
    {   
        $role = $this->find($id);   

        if (!$role) 
            return responseFail(404);

        return $role;
    }
   

    /**
     * 更新role
     *
     * @param $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function renew($request, $id)
    {
        \DB::beginTransaction();
        try {            
            $role = $this->find($id);

            $role->syncPermissions($request->permissions);           

            \DB::commit();

            event(new UpdateStaffRoleEvent($role));

            return responseSuccess('角色权限更新成功', $role);

        } catch (Exception $e) {
            \DB::rollback();
            return responseFail(500, '角色权限更新失败');
        } 
        
    }


    public function privilege()
    {
        //$rows = $this->model->with('users')->where('value','marketing')->get();
        $rows = $this->model->with('users')->get();
        
        return $rows;
    }
    
}